/**
 * Data processor implementation.
 */

#include "processor.h"
#include "../utils/helpers.h"

#include <fstream>
#include <sstream>
#include <stdexcept>
#include <iostream>

namespace core {

DataProcessor::DataProcessor() : processed_count_(0) {
}

DataProcessor::~DataProcessor() {
}

DataProcessor::ProcessResult DataProcessor::process_file(const std::string& file_path) {
    try {
        std::string content = utils::read_file_safely(file_path);
        ProcessResult result = analyze_content(content);
        processed_count_++;
        return result;
    } catch (const std::exception& e) {
        errors_.push_back(e.what());
        throw;
    }
}

DataProcessor::ProcessResult DataProcessor::analyze_content(const std::string& content) {
    ProcessResult result;
    result.length = content.length();
    result.lines = std::count(content.begin(), content.end(), '\n') + 1;
    
    // Count words
    std::istringstream iss(content);
    std::string word;
    size_t word_count = 0;
    while (iss >> word) {
        word_count++;
    }
    result.words = word_count;
    result.analysis_complete = true;
    
    return result;
}

void DataProcessor::save_result(const ProcessResult& result, const std::string& output_path) {
    std::ofstream file(output_path);
    if (!file.is_open()) {
        throw std::runtime_error("Cannot open output file: " + output_path);
    }
    
    file << "{\n";
    file << "  \"length\": " << result.length << ",\n";
    file << "  \"lines\": " << result.lines << ",\n";
    file << "  \"words\": " << result.words << ",\n";
    file << "  \"analysis_complete\": " << (result.analysis_complete ? "true" : "false") << "\n";
    file << "}\n";
    
    file.close();
}

std::vector<DataProcessor::ProcessResult> DataProcessor::batch_process(
    const std::vector<std::string>& file_paths) {
    
    std::vector<ProcessResult> results;
    for (const auto& path : file_paths) {
        try {
            ProcessResult result = process_file(path);
            results.push_back(result);
        } catch (const std::exception&) {
            // Continue processing other files
            continue;
        }
    }
    return results;
}

std::map<std::string, int> DataProcessor::get_statistics() const {
    std::map<std::string, int> stats;
    stats["processed_count"] = static_cast<int>(processed_count_);
    stats["error_count"] = static_cast<int>(errors_.size());
    return stats;
}

} // namespace core